package com.example.netdemo.base

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import androidx.viewbinding.ViewBinding
import com.example.netdemo.LoadingDialog
import com.example.netdemo.viewmodel.LoadingState
import kotlin.reflect.KClass

open abstract class BaseActivity<VB : ViewBinding, VM : BaseViewModel>(private val viewModelClass: KClass<VM>) : AppCompatActivity() {
    private lateinit var loadingDialog: LoadingDialog
    lateinit var binding: VB
    val viewModel: VM by lazy {
        ViewModelProvider(this)[viewModelClass.java]
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding  = getViewBinding()
        setContentView(binding.root)

        initLoadingObserver()
        initView()
        initData()
        setListener()
    }


    protected abstract fun getViewBinding(): VB

    protected abstract fun initView()

    protected abstract fun initData()

    protected abstract fun setListener()

    private fun initLoadingObserver() {
        viewModel.loadingState.observe(this) {
            when (it) {
                is LoadingState.Show -> {
                    showLoading()
                }

                is LoadingState.Hide -> {
                    hideLoading()
                }

                is LoadingState.Message -> {
                    showLoading(it.message)
                }

                else -> {}
            }
        }
    }

    private fun showLoading(message: String = "加载中...") {
        if (!::loadingDialog.isInitialized) {
            loadingDialog = LoadingDialog(this).apply {
                //  设置加载信息
            }
        } else{
            //  设置加载信息
        }
        loadingDialog.showDialog()
    }

    private fun hideLoading() {
        if (::loadingDialog.isInitialized) {
            loadingDialog.dismissDialog()
        }
    }
}